package com.acme.ioniolab.transportfile.implementation;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import com.acme.ioniolab.transportfile.Server;

public class NIOServer implements Server {

	@Override
	public long receiveFile(String fileName, int port) throws IOException {
		long time = 0;
		try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
				FileChannel outputStream = new FileOutputStream(fileName).getChannel()) {
			
			serverSocketChannel.configureBlocking(true);
			serverSocketChannel.bind(new InetSocketAddress(port));
			SocketChannel socket = serverSocketChannel.accept();
			
			time = System.currentTimeMillis();
			
			ByteBuffer bytes = ByteBuffer.allocate(1024);
			socket.read(bytes);
			bytes.rewind();
			long fileSize = bytes.getLong();
			
			outputStream.transferFrom(socket, 0, fileSize);
			
			time = System.currentTimeMillis() - time;
			socket.close();
		}
		return time;
	}

}
